var _id = '',
    _ids = [];
    //_specArr = [];
var login = false;
var uid = '';
//var total = 100;
//var min = 1;
$(function(){

    post({
        url : "/isLogin",
        success : function(data){
            if(!data){
                login = false;
                emptyCart();
            }else{
                login = true;
                post({
                    url:'/member/uid',
                    success:function(data){
                        //console.log(data);
                        uid = data;
                    }
                })
                getCartListData();
            }
        }
    });

    /*$(".go-back").click(function(){
        var _url = localStorage.getItem("cart_return");
        go(_url);
    });*/

});

localStorage.removeItem("invoice_id");

//点击去结算
$(".account .btn ").click(function(){

    if(_ids.length>0){
        //setCookie("customize_cartId",_ids.toString());
        post({
            url:"/customizeOrder/saveOrderCode",
            data:{cartIds:_ids.toString()},
            success:function(data){
                localStorage.setItem("customize_order_return",window.location.href);
                localStorage.setItem("customize_orderCode",data);
                localStorage.setItem("customize_cartIds",_ids.toString());
                go("/mobileorder/order_confirm.html");
            }
        });
    }
});

//获取购物车列表数据
function getCartListData(){
    post({
        url:"/customizeCart/list",
        success: function (data) {
            //console.log(data);
            dealCartGoods(data);
        },
        error:function(msg){
            console.log(msg)
        }
    });
}

//处理购物车列表数据
function dealCartGoods(data){
     var _html = '';
     var amount = 0;
     for(var i=0;i<data.length;i++){
         amount = parseFloat(data[i]["price"]*data[i]["num"]) + parseFloat(data[i]["makeFee"]*data[i]["num"]) + data[i]["designFee"];
         _html += '<div class="list">';
         _html += '<div class="list_detail">';
         if(data[i]["productStatus"] == "SALE_LOWER"){
             _html += '<div class="range left">';
             _html += '<span>失效</span></div>';
         }else{
             _html += '<div style="background-image: url(img/round.png);" class="range left">';
             _html += '<input type="checkbox" class="single_chk" data-price="'+amount+'" data-num="'+data[i]["num"]+'" data-id="'+data[i]["id"]+'"/></div>';

         }

         _html += '<div class="img left"><img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+data[i]["productUrl"]+'">';
         _html += '<div class="customize-type">'+(data[i]["designType"] == "DESIGN"?"定制":"原厂")+'</div>';
         _html += '</div><div class="info left">';
         _html += '<p class="more_single"><a href="/customize/newDesign.html?productid='+data[i]["productId"]+'&inviter='+uid+'">'+data[i]["productName"]+'</a></p>';
         _html += '<p class="price more_single">￥<a>'+(data[i]["price"]).toFixed(2)+'</a><span class="right" style="margin-right: 0.01rem;">X&nbsp;';
         _html += data[i]["num"]+'</span></p>';
         //for(var j=0;j<data[i]["specifications"].length;j++){
         //    _html += data[i]["specifications"][j]["specValue"]+"&nbsp;";
         //}
         _html += '<p class="more_single">'+data[i]["manufacturerSpecification"]+'</p>';
         _html += '<p class="more_single">'+data[i]["designerSpecification"]+'</p>';
         _html += '</div></div>';
         if(data[i]["designType"] == "DESIGN"){
             _html += '<div class="designer-info"><p>设计商：'+data[i]["designer"]+'</p>';
             _html += '<p>设计：<span>￥'+returnFloat(data[i]["designFee"])+'</span></p>';
             _html += '<p>制作：<span>￥'+returnFloat(data[i]["makeFee"])+'</span><a class="right" style="color: #666;" href="javascript:;">X&nbsp;'+data[i]["num"]+'</a></p>';
             _html += '</div>';
         }
         _html += '<div class="handle">';
         _html += '<span class="left amount">小计：<a>￥'+returnFloat(amount)+'</a></span>';
         _html += '<span class="right p_delete" data-id="'+data[i]["id"]+'">删除</span>';
         if(data[i]["productStatus"] != "SALE_LOWER"){
             _html += '<span class="right p_editor" data-productid="'+data[i]["productId"]+'" data-id="'+data[i]["id"]+'" data-num="'+data[i]["num"]+'" data-type="'+data[i]["designType"]+'">编辑</span>';
         }

         _html += '</div></div>';
     }

     if(data.length ==0){
         emptyCart();
     }else{
         $(".main").html(_html);
     }

     selcetProduct();//勾选商品

     deleteProduct();//删除商品

     $(".p_editor").click(function(){
         _id = $(this).data("id");
         var productId = $(this).data("productid");
         var type = $(this).data("type") == "DESIGN"?"DESIGN":"ORIGINAL";
         //type = type == "DESIGN"?"DESIGN":"ORIGINAL";
         localStorage.setItem('selectdesign_goBackUrl',window.location.href)
         go("/customize/gocustomize/selectDesign.html?productid="+productId+"&designType="+type+"&cartid="+_id)
     });

 }

//勾选购物车商品
 function selcetProduct(){

     var chk=document.querySelectorAll(".single_chk");  //单选按钮
     var chkAll=document.querySelector(".selectAll");
     var flag=true;
     $(".single_chk").click(function(){//单选
         flag=true;
         for(var k=0;k<chk.length;k++){
             if(chk[k].checked==false){
                 flag=false;
             }
         }
         countPrice();
     });

     $(".selectAll").click(function(){  //全选
         $(".single_chk").prop("checked",chkAll.checked);
         countPrice();
     });
 }

//计算总价格
function countPrice(){

     var flag = true;
     var _price=0;
     var num = 0;
     var chkAll=document.querySelector(".selectAll");
     _ids =[];
     $(".single_chk").each(function(index){
         if($(this).prop("checked")){
             _price += $(this).data("price");
             num += $(this).data("num");
             _ids.push($(this).data("id"));
             $(this).parent().addClass("back-select");
         }else{
             $(this).parent().removeClass("back-select");
             flag = false;
         }
     });
     chkAll.checked=flag;
     if(flag == true){
         $(".icon_cart").addClass("back-select");
     }else{
         $(".icon_cart").removeClass("back-select");
     }
     $(".total_price").text("￥"+_price.toFixed(2));
     $(".account .btn span").text("("+num+")");
 }

//删除商品
function deleteProduct(){

    var cartId = '';
    var _this = '';
    $(".main").delegate(".p_delete","click",function(){
        cartId = $(this).data("id");
        _this = $(this);
        $('.gat_background').removeClass('tab');
        $('.gat_alert').addClass('animated slideInDown');

    });

    $('.gat_alert_affirm').click(function () {
        post({
            url:"/customizeCart/"+cartId+"/delete",
            success:function(data){
                _this.parent().parent().remove();

                var _inner = $(".main").html();
                if(_inner == ""){
                    emptyCart();
                }
                $('.gat_background').addClass('tab');
            }
        });
    });

    $('.gat_alert_cancel').click(function () {
        $('.gat_background').addClass('tab');
    });
}

//购物车为空时显示的内容
function emptyCart(){
    var _h = '<div class="empty"><img src="../../common/img/gouwuche.png">';
    _h += '<p>&nbsp;&nbsp;购物车是空的～</p></div>';
    $(".main").html(_h);
}

